package com.llyb.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llyb.lease.common.exception.LeaseException;
import com.llyb.lease.common.result.ResultCodeEnum;
import com.llyb.lease.model.entity.*;
import com.llyb.lease.model.enums.ItemType;
import com.llyb.lease.web.admin.mapper.*;
import com.llyb.lease.web.admin.service.*;
import com.llyb.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.llyb.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.llyb.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.llyb.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.llyb.lease.web.admin.vo.graph.GraphVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.sql.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;


/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private ApartmentLabelService apartmentLabelService;

    @Autowired
    private ProvinceInfoMapper provinceInfoMapper;

    @Autowired
    private CityInfoMapper cityInfoMapper;

    @Autowired
    private DistrictInfoMapper districtInfoMapper;

    @Autowired
    private RoomInfoService roomInfoService;

    @Override
    public void customAll(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.customAll(page,queryVo);
    }

    @Override
    public boolean customSavaOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {
        boolean isUpdated = apartmentSubmitVo.getId() != null;

        // 前端没给省份名字，所以需要查询
        String provinceName = provinceInfoMapper.selectById(apartmentSubmitVo.getProvinceId()).getName();
        String cityName = cityInfoMapper.selectById(apartmentSubmitVo.getCityId()).getName();
        if (!ObjectUtils.isEmpty(apartmentSubmitVo.getDistrictId())) {
            String districtName = districtInfoMapper.selectById(apartmentSubmitVo.getDistrictId()).getName();
            apartmentSubmitVo.setDistrictName(districtName);
        }
        apartmentSubmitVo.setProvinceName(provinceName);
        apartmentSubmitVo.setCityName(cityName);


        saveOrUpdate(apartmentSubmitVo);
        Long id = apartmentSubmitVo.getId();

        // if 是更新的话，删除四个中间表
        if (isUpdated) {
            updateMiddleInfo(id);
        }

        // 保存四个表
        if (!CollectionUtils.isEmpty(apartmentSubmitVo.getFacilityInfoIds())) {
            ArrayList<ApartmentFacility> facilityList = new ArrayList<>();
            for (Long facilityInfoId : apartmentSubmitVo.getFacilityInfoIds()) {
                ApartmentFacility build = ApartmentFacility.builder().apartmentId(id).facilityId(facilityInfoId).build();
                facilityList.add(build);
            }
            apartmentFacilityService.saveBatch(facilityList);
        }

        if (!CollectionUtils.isEmpty(apartmentSubmitVo.getFeeValueIds())) {
            ArrayList<ApartmentFeeValue> feeValuesList = new ArrayList<>();
            for (Long feeValueId : apartmentSubmitVo.getFeeValueIds()) {
                ApartmentFeeValue build = ApartmentFeeValue.builder().apartmentId(id).feeValueId(feeValueId).build();
                feeValuesList.add(build);
            }
            apartmentFeeValueService.saveBatch(feeValuesList);
        }

        if (!CollectionUtils.isEmpty(apartmentSubmitVo.getLabelIds())) {
            ArrayList<ApartmentLabel> labelList = new ArrayList<>();
            for (Long labelId : apartmentSubmitVo.getLabelIds()) {
                ApartmentLabel build = ApartmentLabel.builder().apartmentId(id).labelId(labelId).build();
                labelList.add(build);
            }
            apartmentLabelService.saveBatch(labelList);
        }

        if (!CollectionUtils.isEmpty(apartmentSubmitVo.getGraphVoList())) {
            ArrayList<GraphInfo> graphList = new ArrayList<>();
            for (GraphVo graphVo : apartmentSubmitVo.getGraphVoList()) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemId(id);
                graphInfo.setItemType(ItemType.APARTMENT);
                graphList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphList);
        }


        return true;
    }

    private void updateMiddleInfo(Long id) {
        LambdaQueryWrapper<GraphInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.APARTMENT);
        lambdaQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoService.remove(lambdaQueryWrapper);

        LambdaQueryWrapper<ApartmentFacility> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(ApartmentFacility::getApartmentId, id);
        apartmentFacilityService.remove(lambdaQueryWrapper1);

        LambdaQueryWrapper<ApartmentLabel> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelService.remove(lambdaQueryWrapper2);

        LambdaQueryWrapper<ApartmentFeeValue> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper3.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueService.remove(lambdaQueryWrapper3);
    }

    @Override
    public ApartmentDetailVo customGetById(Long id) {
        return apartmentInfoMapper.customSelectById(id);
    }

    @Override
    public void customRemoveById(Long id) {
        // 是否有公寓关联的房间，有的话，不允许删除
        LambdaQueryWrapper<RoomInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        long count = roomInfoService.count(lambdaQueryWrapper);

        if (count>0) {
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        // 删除中间表
        updateMiddleInfo(id);

        // 删除公寓
        removeById(id);
    }

}




